/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.app.service.google.impl;

import com.google.gson.Gson;
import java.net.URLDecoder;
import java.util.Map;
import org.apache.log4j.Logger;
import org.app.dao.M_KeywordDAO;
import org.app.dao.M_WebsiteAccountDAO;
import org.app.dao.impl.M_KeywordDAOImpl;
import org.app.dao.impl.M_WebsiteAccountDAOImpl;
import org.app.dto.google.ResponseDataJson;
import org.app.model.M_Keyword;
import org.app.model.M_WebsiteAccount;
import org.app.model.QueueURLs;
import org.app.service.google.IGoogleService;
import org.app.service.google.GoogleSearch;
import org.app.utils.Utils;
import org.gui.AutoDownloadMovieGUI;
import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author LamLe
 */
public class GoogleDisableJS_ServiceImpl extends GoogleSearch implements IGoogleService {

    private static Logger logger = Logger.getLogger(GoogleDisableJS_ServiceImpl.class);
    private Map<String, String> cookies;
    private M_WebsiteAccountDAO websiteAccountDAO;
    private M_KeywordDAO keywordDAO;

    public GoogleDisableJS_ServiceImpl(AutoDownloadMovieGUI main) {
        super(main);
        websiteAccountDAO = new M_WebsiteAccountDAOImpl();
        keywordDAO = new M_KeywordDAOImpl();
    }

    @Override
    public ResponseDataJson search(String movieName) throws Exception {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public ResponseDataJson search(String movieName, int page, ResponseDataJson json) throws Exception {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public ResponseDataJson search24(String movieName) throws Exception {
        ResponseDataJson results = new ResponseDataJson();
        try {
            // persist keyword
            M_Keyword keyword = searchKeyword(movieName);

            // init first time or restore from cookies browser.properties
            M_WebsiteAccount google = initFirstTime();

            //

            movieName = generateUrl(movieName);
            movieName = "&q=" + movieName;

            Connection conn = Jsoup.connect("http://www.google.com.vn/search?hl=vi&gbv=1" + movieName)
                    .cookies(google.getCookie());
            Utils.initRequestHeader(conn);
            Response res = conn.execute();
            google.setCookies(res.cookies());
            htmlParse(conn.get());
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace(System.out);
            throw e;
        }
        return results;
    }

    private M_WebsiteAccount initFirstTime() throws Exception {
        // first time
        M_WebsiteAccount google = websiteAccountDAO.getWebsiteByDomain("google.com.vn");
        if (google == null) {
            google = new M_WebsiteAccount();
            
            String googleUrl = "http://www.google.com.vn/";
            Connection conn = Jsoup.connect(googleUrl);
            Utils.initRequestHeader(conn);

            Response initGoogle = conn.execute();
            cookies = initGoogle.cookies();

            Document doc = initGoogle.parse();
            System.out.println("google init : " + doc.toString());
            Elements inputs = doc.select("form input");
            for (Element input : inputs) {
                System.out.println("Name : " + input.attr("name"));
                System.out.println("Value : " + input.attr("value"));
            }
            //els.select(googleUrl)
            Gson gson = new Gson();
            // write to google db
            google.setCookies(gson.toJson(cookies));
            google.setActive(true);
            google.setDomainName(Utils.getDomainName(googleUrl));

            websiteAccountDAO.save(google);
        }
        return google;
    }

    private ResponseDataJson parseGoogleResult(String html) {
        ResponseDataJson results = new ResponseDataJson();
        QueueURLs queue = QueueURLs.getInstance();
        try {
            String s = html;
            String str[] = s.split("<h3 class=\"r\">");
            for (String q : str) {
                String str_[] = q.split("</h3>");
                for (String w : str_) {
                    if (w.indexOf("<a href=") == 0) {
                        w = w.replace("<a href=\"/url?q=", "");
                        w = w.substring(0, w.indexOf("&amp;sa="));
                        // link from google
                        logger.info(w);
                        queue.add(w);
                    }
                }
            }
            String pages[] = s.split("<span class=\"csb\"");
            for (String p : pages) {
                if (p.contains("search?q=") && p.contains("background-position:") && p.contains("class=\"fl\">")) {
                    logger.info(p.substring(p.indexOf("<a href=\"") + 9, p.indexOf("\" class=\"fl\">")));
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
        return results;
    }

//    private void htmlParse(String html) {
//        try {
//            //File in = new File("resources/result.html");
//            //Document doc = Jsoup.parse(in, "UTF-8");
//            Document doc = Jsoup.parse(html);
//            Elements links = doc.select("div#ires li h3.r a");
//            for (Element e : links) {
//                String url = e.select("a").attr("href");
//                url = url.substring(7, url.indexOf("&sa=U"));
//                url = URLDecoder.decode(url, "UTF-8");
//                logger.info(url);
//                QueueURLs.add(url);
//            }
//        } catch (Exception e) {
//            e.printStackTrace(System.out);
//        }
//    }
    private void htmlParse(Document doc) {
        try {
            Elements links = doc.select("div#ires li h3.r a");
            QueueURLs queue = QueueURLs.getInstance();
            for (Element e : links) {
                String url = e.select("a").attr("href");
                url = url.substring(7, url.indexOf("&sa=U"));
                url = URLDecoder.decode(url, "UTF-8");
                logger.info(url);
                queue.add(url);
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }

    private M_Keyword searchKeyword(String movieName) throws Exception {
        M_Keyword keyword = keywordDAO.searchKeyword(movieName);
        if (keyword == null) {
            keyword = new M_Keyword();
            keyword.setKeyword(movieName);

            keywordDAO.save(keyword);
        }
        return keyword;
    }
}
